package com.itzyf.pokemondata.activity.team

import android.app.Activity
import android.content.Intent
import android.text.Html
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.activity.panel.PanelDetailActivity
import com.itzyf.pokemondata.activity.panel.SelectPokemonActivity
import com.itzyf.pokemondata.bean.DbTeamDo
import com.itzyf.pokemondata.bean.ResistanceDo
import com.itzyf.pokemondata.utils.ResistanceUtils
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_gallery.*
import org.litepal.LitePal
import java.util.*
import kotlin.collections.ArrayList

/**
 * @author 依风听雨
 * @version 创建时间：2019/02/15 16:04
 */
class TeamActivity : BaseActivity() {
    private val property = arrayOf(
        "普", "格", "飞", "毒", "地", "岩",
        "虫", "鬼", "钢", "火", "水", "草",
        "电", "超", "冰", "龙", "恶", "妖"
    )
    var mDatas: MutableList<DbTeamDo?> = ArrayList()
    private var isResistance = false
    private val data: MutableList<MutableList<String>> = ArrayList()
    private lateinit var mAdapter: QuickAdapter

    private var fontSize = 12f

    /**
     * 当前编队
     */
    private var currentNo = 0

    override fun handlerActivity() {
//        toolbar.visibility=View.GONE
        for (row in ResistanceUtils) {
            val rowNew: MutableList<String> = ArrayList()
            for (item in row) {
                rowNew.add(item)
            }
            data.add(rowNew)
        }

        mAdapter = QuickAdapter(R.layout.item_team2, mDatas)
        val layoutManager = LinearLayoutManager(this)
        rv_list.layoutManager = layoutManager
        rv_list.adapter = mAdapter

        val helper = ItemTouchHelper(ItemDrag())
        helper.attachToRecyclerView(rv_list)
        fontSize = sp.getFloat("teamFontSize", 12f)
        mAdapter.setOnItemClickListener { _, _, position ->
            val builder = QMUIDialog.CheckableDialogBuilder(this)
                .addItems(
                    arrayOf(
                        "查看",
                        "编辑",
                        "删除",
                        if (toolbar.visibility == View.GONE) "显示标题栏" else "隐藏标题栏"
                    )
                ) { dialog, which ->
                    when (which) {
                        0 -> {
                            val intent = Intent(this@TeamActivity, PanelDetailActivity::class.java)
                            intent.putExtra("objId", mDatas[position]?.objectId)
                            startActivity(intent)
                        }
                        1 -> {
                            val intent = Intent(this, EditPokemonActivity::class.java)
                            intent.putExtra("objId", mDatas[position]!!.objectId)
                            intent.putExtra("id", mDatas[position]!!.id)
                            startActivityForResult(intent, 0x2)
                        }
                        2 -> delete(position)
                        3 -> {
                            if (toolbar.visibility == View.GONE) {
                                toolbar.visibility = View.VISIBLE
                            } else {
                                toolbar.visibility = View.GONE
                            }
                        }
                    }
                    dialog.dismiss()
                }
            builder.show()
        }

        queryDatas()

        showTipMessage()
    }


    private fun delete(position: Int) {
        showAlertDialog(
            "提示", "是否删除？", "删除"
        ) { _, _ ->
            LitePal.delete(DbTeamDo::class.java, mDatas[position]!!.id)
            queryDatas()
        }
    }

    private fun deleteAll() {
        showAlertDialog(
            "提示", "是否清空当前队伍数据？", "清空"
        ) { _, _ ->
            LitePal.deleteAll(DbTeamDo::class.java, "no = ?", currentNo.toString())
            queryDatas()
        }
    }

    /**
     * 查询数据
     */
    fun queryDatas() {
        val name = sp.getString("team$currentNo", "")
        val defaultName = if (!name.isNullOrEmpty()) name else "队伍${currentNo + 1}"
        setTitle(defaultName)

        mDatas.clear()
        mDatas.addAll(
            LitePal.where("no = ?", currentNo.toString())
                .order("sort asc")
                .find(DbTeamDo::class.java)
        )
        if (isResistance) {
            val weakness = mutableMapOf<String, Int>()
            val resistance = mutableMapOf<String, Int>()
            for (teamDo in mDatas) {
                teamDo?.let {
                    var attr = it.attr.trim()
                    if (it.attr.length == 18) {
                        attr = attr.substring(0, 1)
                    }
                    teamDo.resistanceDoList = calculateResistance(attr)
                    for (r in it.resistanceDoList) {
                        if (r.value > 1) {
                            weakness[r.property] = weakness[r.property]?.plus(1) ?: 1
                        } else if (r.value < 1) {
                            resistance[r.property] = resistance[r.property]?.plus(1) ?: 1
                        }
                    }
                }
            }
            val sb = StringBuffer("<font color=#FF0000>综合弱点：")
            for ((key, value) in weakness) {
                sb.append("$value$key ")
            }
            sb.append("</font><br/><font color=#0000FF>综合抵抗：")
            for ((key, value) in resistance) {
                sb.append("$value$key ")
            }
            sb.append("</font>")
            tvWeaknessList.text = Html.fromHtml(sb.toString())
            llResistance.visibility = View.VISIBLE
        } else {
            llResistance.visibility = View.GONE
        }
        mAdapter.notifyDataSetChanged()
    }

    override fun getContentViewId() = R.layout.activity_gallery

    override fun getToolbarTitle() = "队伍预设"

    internal inner class QuickAdapter(layoutResId: Int, data: List<DbTeamDo?>) :
        BaseQuickAdapter<DbTeamDo, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: DbTeamDo?) {
            item?.let {
                var attr = it.attr.trim()
                if (it.attr.length == 18) {
                    attr = attr.substring(0, 1)
                }
                helper.setText(R.id.text, "${it.name}($attr)")
                helper.setText(R.id.tvProp, it.prop)
                helper.setText(R.id.tvSkill1, it.skill1)
                helper.setText(R.id.tvSkill2, it.skill2)
                helper.setText(R.id.tvSkill3, it.skill3)
                helper.setText(R.id.tvSkill4, it.skill4)
                helper.setText(R.id.tvFeature, it.feature)
                helper.setText(R.id.tvCharacter, it.character)
                helper.setText(R.id.tvEffort, it.effor)
                helper.setText(R.id.tvZ, it.z)
                if (isResistance) {
//                    val resistance = calculateResistance(attr)
                    var html = "抵抗："
                    var html2 = "弱点："
                    for (r in it.resistanceDoList) {
                        val value = r!!.value
                        when (value) {
                            0.0 -> html += "<font color=#000000>${r.property}</font>"
                            2.0 -> html2 += "<font color=#FF0000>${r.property}</font>"
                            4.0 -> html2 += "<strong><font color=#FF0000>${r.property}</font></strong>"
                            0.5 -> html += "<font color=#0000FF>${r.property}</font>"
                            0.25 -> html += "<strong><font color=#0000FF>${r.property}</font></strong>"
                        }
                    }
                    helper.setText(R.id.tvResistance, Html.fromHtml("$html&emsp;&emsp;$html2"))
                }
                helper.setGone(R.id.tvResistance, isResistance)
            }
            val root = helper.getView<LinearLayout>(R.id.root)
            recursionTravelView(root)
        }

        private fun recursionTravelView(rootView: ViewGroup) {
            for (i in 1..rootView.childCount) {
                val view = rootView.getChildAt(i - 1)
                if (view is TextView) {
                    view.textSize = fontSize
                } else if (view is ViewGroup) {
                    recursionTravelView(view)
                }
            }
        }
    }

    override
    fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.team, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        item?.let {
            when (it.itemId) {
                R.id.action_team -> {
                    if (LitePal.where(
                            "no = ?",
                            currentNo.toString()
                        ).count(DbTeamDo::class.java) >= 6
                    ) {
                        showToast("已达最大上限值")
                        return super.onOptionsItemSelected(item)
                    }
                    startActivityForResult(Intent(this, SelectPokemonActivity::class.java), 0x1)
                    return true
                }
                R.id.action_switch -> isResistance = !isResistance
                R.id.action_team_switch -> switchTeam()
                R.id.action_team_remark -> setRemark()
//                R.id.action_team3 -> currentNo = 2
                R.id.action_big -> {
                    fontSize += 1
                    sp.edit().putFloat("teamFontSize", fontSize).apply()
                    mAdapter.notifyDataSetChanged()
                }
                R.id.action_small -> {
                    fontSize -= 1
                    sp.edit().putFloat("teamFontSize", fontSize).apply()
                    mAdapter.notifyDataSetChanged()
                }
                R.id.action_delete -> deleteAll()
                else -> {
                }
            }
            queryDatas()
        }
        return super.onOptionsItemSelected(item)
    }

    /**
     * 切换队伍
     */
    private fun switchTeam() {
        val names = ArrayList<String>(10)
        for (i in 0..9) {
            val name = sp.getString("team$i", "")
            names.add(if (!name.isNullOrEmpty()) name else "队伍${i + 1}")
        }

        val builder = QMUIDialog.CheckableDialogBuilder(this)
            .addItems(names.toTypedArray()) { dialog, which ->
                currentNo = which
                queryDatas()
                dialog.dismiss()
            }
        builder.show()
    }

    /**
     * 设置队伍备注
     */
    private fun setRemark() {
        val name = sp.getString("team$currentNo", "")
        val defaultName = if (!name.isNullOrEmpty()) name else "队伍${currentNo + 1}"

        val builder = QMUIDialog.EditTextDialogBuilder(this)
            .setDefaultText(defaultName)
            .setTitle("队伍备注")
            .addAction("取消") { dialog, _ ->
                dialog.dismiss()
            }
        builder.addAction("保存") { dialog, _ ->
            if (builder.editText.toString().isNotEmpty()) {
                sp.edit().putString("team$currentNo", builder.editText.text.toString()).apply()
            }
            dialog.dismiss()
        }

        builder.show()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0x2) {
                queryDatas()
                return
            }
            data?.let {
                if (requestCode == 0x1) {
                    val intent = Intent(this, EditPokemonActivity::class.java)
                    intent.putExtra("objId", it.getStringExtra("objId"))
                    intent.putExtra("currentNo", currentNo)
                    startActivityForResult(intent, 0x2)
                    queryDatas()
                }
            }
        }

    }

    /**
     * 计算抗性
     */
    private fun calculateResistance(attr: String): MutableList<ResistanceDo?> {
        val mResistanceDatas: MutableList<ResistanceDo?> = ArrayList()
        var index = property.indexOf(attr.substring(0, 1))
        if (index == -1) {
            showToast("精灵属性异常，请反馈")
            index = 0
        }
        //单属性
        if (attr.length == 1 || attr.length == 18) {
            for (i in 0..17) {
                val p1 = data[i][index].toDouble()
                mResistanceDatas.add(ResistanceDo(property[i], p1))
            }
        } else {
            var index1 = property.indexOf(attr.substring(1, 2))
            if (index1 == -1) {
                showToast("精灵属性异常，请反馈")
                index1 = 0
            }
            for (i in 0..17) {
                val p1 = data[i][index].toDouble()
                val p2 = data[i][index1].toDouble()
                mResistanceDatas.add(ResistanceDo(property[i], p1 * p2))
            }
        }
        return mResistanceDatas
    }

    private fun showTipMessage() {
        if (!sp.getBoolean("isTeamTips2", false))
            QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("右上角按钮添加精灵，长按可编辑和删除精灵")
                .addAction(
                    "确定"
                ) { dialog, _ ->
                    sp.edit().putBoolean("isTeamTips2", true).apply()
                    dialog.dismiss()
                }
                .show()
    }

    internal inner class ItemDrag : ItemTouchHelper.Callback() {
        override fun getMovementFlags(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder
        ) = makeMovementFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0)


        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            val fromPosition = viewHolder.adapterPosition
            val toPosition = target.adapterPosition
            Collections.swap(mDatas, fromPosition, toPosition)
            mAdapter.notifyItemMoved(fromPosition, toPosition)
            return true
        }


        override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
            super.clearView(recyclerView, viewHolder)
            for ((index, item) in mDatas.withIndex()) {
                item?.sort = index
                item?.save()
            }
        }

        override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

        }

    }

}